<template>
    <div class="mod-config">
        <!-- Overview Statistics -->
        <div class="overview-stats">
            <el-card v-for="stat in overviewStats" :key="stat.label" class="stat-card">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
                <!-- <div class="stat-trend" :class="{ 'positive': stat.trend > 0 }">
                    {{ stat.trend > 0 ? '+' : '' }}{{ stat.trend }}%
                </div> -->
            </el-card>
        </div>

        <!-- Filter Section -->
        <el-card class="filter-section">
            <el-form :model="filterForm" inline>
                <el-form-item label="时间范围">
                    <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="领域">
                    <!-- <el-select v-model="filterForm.domain" placeholder="请选择领域">
                        <el-option v-for="option in domainOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
                    </el-select> -->

                    <el-tree-select v-model="specialtyTagId" class="form-input" :data="specialtyTags" filterable
                        clearable check-strictly placeholder="请选择专业领域"
                        :props="{ value: 'id', label: 'tagName', children: 'children' }" @clear="handleClear('field')"
                        @change="handleChange" />
                    <!-- style="width: 380px;"  -->


                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleFilterChange" >筛选</el-button>
                    <el-button @click="handleReset"  class="ml-4">重置</el-button>
                    <!-- <el-button @click="handleExport" :loading="loading" type="success">导出数据</el-button> -->
                </el-form-item>
            </el-form>
        </el-card>

        <!-- Charts Grid -->
        <div class="charts-grid">
            <el-card class="chart-card">
                <template #header>
                    <div class="chart-title">解答数量分布</div>
                </template>
                <div ref="answersChart" class="chart"></div>
            </el-card>

            <el-card class="chart-card">
                <template #header>
                    <div class="chart-title">采纳率分布</div>
                </template>
                <div ref="acceptanceChart" class="chart"></div>
            </el-card>

            <el-card class="chart-card">
                <template #header>
                    <div class="chart-title">活跃度趋势</div>
                </template>
                <div ref="activityChart" class="chart"></div>
            </el-card>

            <el-card class="chart-card">
                <template #header>
                    <div class="chart-title">领域分布</div>
                </template>
                <div ref="domainChart" class="chart"></div>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, getCurrentInstance, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as echarts from 'echarts';
import { getSpecialtyTag, getSpecialtyTagTree } from '@/axios/api/expert'
import { getOverviewStats, getEchartData } from '@/axios/api/statistics'


const { proxy } = getCurrentInstance();

const dataForm = reactive({
    key: "",
    type: "",
});
const dataList = ref([]);
const pageIndex = ref(1);
const pageSize = ref(10);
const totalPage = ref(0);
const dataListLoading = ref(false);
const specialtyTagId = ref('')
// Filter form data
const filterForm = reactive({
    dateRange: [new Date(new Date().setMonth(new Date().getMonth() - 1)), new Date()],
    domain: "",
});

// Domain options
const domainOptions = [
    { label: "技术开发", value: "tech" },
    { label: "产品设计", value: "product" },
    { label: "市场营销", value: "marketing" },
    { label: "运营管理", value: "operations" },
    { label: "人力资源", value: "hr" },
];

// Overview statistics data
const overviewStats = reactive([
    { label: "总专家数", value: "0", trend: 0 },
    { label: "本月活跃专家", value: "0", trend: 0 },
    { label: "平均采纳率", value: "0%", trend: 0 },
    { label: "本月解答总数", value: "0", trend: 0 },
]);

// 获取概览统计数据
const fetchOverviewStats = async () => {
    try {
        const res = await getOverviewStats()
        console.log('概览统计数据:', res)
        if (res.code === 0 && res.data) {
            const { totalExperts, activeExperts, adoptionRate, totalAnswers } = res.data;
            overviewStats[0].value = totalExperts.toString();
            overviewStats[1].value = activeExperts.toString();
            overviewStats[2].value = adoptionRate + '%';
            overviewStats[3].value = totalAnswers.toString();
        }
    } catch (error) {
        console.error('获取概览统计数据失败:', error)
    }
};

// Chart references
const loading = ref(false);
const answersChart = ref(null);
const acceptanceChart = ref(null);
const activityChart = ref(null);
const domainChart = ref(null);

// 处理筛选按钮点击
const handleFilterChange = async () => {
    loading.value = true;
    try {
        // 并行调用所有图表的数据获取
        await Promise.all([
            getDataList('/expert/statistics/answer-count-distribution', answersChart),
            getDataList('/expert/statistics/adoption-rate-distribution', acceptanceChart),
            getDataList('/expert/statistics/activity-trend', activityChart),
            getDataList('/expert/statistics/specialty-distribution', domainChart)
        ]);

    } catch (error) {
        console.error('更新图表失败:', error);
    } finally {
        loading.value = false;
    }
};

// 处理重置按钮点击
const handleReset = () => {
    filterForm.dateRange = [new Date(new Date().setMonth(new Date().getMonth() - 1)), new Date()];
    filterForm.domain = "";
    specialtyTagId.value = '';
    handleFilterChange();
};

// 图表配置
const chartConfigs = {
    answers: {
        color: '#409EFF',
        type: 'bar',
        barWidth: '60%'
    },
    acceptance: {
        color: '#67C23A',
        type: 'bar',
        barWidth: '60%'
    },
    activity: {
        color: '#E6A23C',
        type: 'line',
        smooth: true
    },
    domain: {
        type: 'pie',
        radius: ['40%', '70%'],  // 设置成环形图，更好地利用空间
        avoidLabelOverlap: true, // 开启标签自动避让
        label: {
            formatter: '{b}\n{d}%',  // 标签显示名称和百分比
            overflow: 'break',  // 文字超出时换行
            lineHeight: 14  // 行高
        },
        labelLine: {
            length: 10,  // 视觉引导线第一段长度
            length2: 10,  // 视觉引导线第二段长度
            smooth: true  // 平滑视觉引导线
        }
    }
};

// 推荐专家数据
const recommendExperts = ref([])

// 处理筛选参数
const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};

// 获取Echarts数据并更新图表
const getDataList = async (url, chartRef) => {
    if (!chartRef.value) return;
    const params = {
        startDate: formatDate(filterForm.dateRange?.[0]),
        endDate: formatDate(filterForm.dateRange?.[1]),
        specialtyTagId: specialtyTagId.value || ''
    };

    try {
        const res = await getEchartData(url, params)
        if (res.code === 0 && res.data) {
            const chartInstance = echarts.getInstanceByDom(chartRef.value);
            if (chartInstance) {
                const chartType = url.includes('specialty-distribution') ? 'domain' :
                    url.includes('answer-count') ? 'answers' :
                        url.includes('adoption-rate') ? 'acceptance' : 'activity';

                const config = chartConfigs[chartType];
                const chartData = res.data;

                const option = {
                    tooltip: {
                        trigger: config.type === 'pie' ? 'item' : 'axis'
                    },
                    series: [{
                        type: config.type,
                        data: config.type === 'pie' ? chartData.data : chartData.series,
                        ...config,
                        itemStyle: config.color ? { color: config.color } : undefined
                    }]
                };

                if (config.type !== 'pie') {
                    option.xAxis = {
                        type: 'category',
                        data: chartData.xaxis,
                        axisLabel: { interval: 0, rotate: 30 }
                    };
                    option.yAxis = { type: 'value' };
                } else {
                    option.legend = {
                        type: 'scroll',
                        orient: 'vertical',
                        right: '4%',
                        top: 'center',
                        itemWidth: 10,
                        itemHeight: 10,
                        textStyle: {
                            fontSize: 12,
                            overflow: 'truncate',
                            width: 100  // 图例文字最大宽度
                        }
                    };
                    // 调整图表位置以适应图例
                    option.series[0].center = ['40%', '50%'];
                }
                chartInstance.setOption(option);
            }
        } else {
            ElMessage.error(res?.msg || '获取数据失败');
        }
    } catch (error) {
        console.error('获取Echart数据失败:', error)
    }
};

// 专业领域标签列表
const specialtyTags = ref([])
// 获取专业领域标签树
const fetchSpecialtyTags = async () => {
    try {
        const res = await getSpecialtyTagTree()
        if (res.code === 0 && res.data) {
            specialtyTags.value = res.data
        }
    } catch (error) {
        console.error('获取专业领域标签树失败:', error)
    }
}

// 处理选择框的变化事件
const handleChange = () => {
    //   emit('change') // 触发变化事件
}



// 处理清除事件
const handleClear = (field) => {
    switch (field) {
        case 'search':
            emit('update:search', '')
            break
        case 'field':
            emit('update:field', '')
            break
    }
    emit('change') // 触发变化事件
}



// 获取推荐专家
async function fetchRecommendExperts(specialtyTagIds) {
    try {
        const res = await get('expert/recommend', { specialtyTagIds })
        if (res.code === 0 && Array.isArray(res.data)) {
            recommendExperts.value = res.data
        } else {
            recommendExperts.value = []
        }
    } catch (e) {
        recommendExperts.value = []
    }
}

// 获取专家统计数据
// const fetchExpertStatistics = async () => {
//     try {
//         const res = await getExpertStatistics()
//         if (res.code === 0 && res.data) {
//             console.log(res.data)
//         }
//     } catch (error) {
//         console.error('获取专家统计数据失败:', error)
//     }
// }

// 获取数据列表
// function getDataList() {
//     dataListLoading.value = true;
//     proxy
//         .$http({
//             url: proxy.$http.adornUrl("/admin/report/list"),
//             method: "get",
//             params: proxy.$http.adornParams({
//                 page: pageIndex.value,
//                 limit: pageSize.value,
//                 key: dataForm.key,
//                 type: dataForm.type,
//             }),
//         })
//         .then(({ data }) => {
//             if (data && data.code === 0) {
//                 dataList.value = data.page.list;
//                 totalPage.value = data.page.totalCount;
//             } else {
//                 dataList.value = [];
//                 totalPage.value = 0;
//             }
//             dataListLoading.value = false;
//         });
// }

// Chart实例引用
let answersInstance = null;
let acceptanceInstance = null;
let activityInstance = null;
let domainInstance = null;

// 初始化和resize
function initCharts() {
    // 销毁旧实例避免重复绑定
    if (answersInstance) answersInstance.dispose();
    if (acceptanceInstance) acceptanceInstance.dispose();
    if (activityInstance) activityInstance.dispose();
    if (domainInstance) domainInstance.dispose();

    // 初始化图表实例
    answersInstance = echarts.init(answersChart.value);
    acceptanceInstance = echarts.init(acceptanceChart.value);
    activityInstance = echarts.init(activityChart.value);
    domainInstance = echarts.init(domainChart.value);

    // 设置基础配置
    [answersInstance, acceptanceInstance, activityInstance, domainInstance].forEach(instance => {
        instance.setOption({
            tooltip: { trigger: 'axis' },
            grid: {
                top: '10%',
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            }
        });
    });

    // 立即获取数据
    handleFilterChange();
}

// resize处理
function resizeCharts() {
    [answersInstance, acceptanceInstance, activityInstance, domainInstance].forEach(instance => {
        instance && instance.resize();
    });
}

// 监听窗口大小变化，调整图表大小
let resizeListener = () => {
    resizeCharts();
};

// 在mounted时初始化图表和事件监听
onMounted(() => {
    nextTick(() => {
        initCharts();
        fetchSpecialtyTags();
        fetchOverviewStats();
        window.addEventListener('resize', resizeListener);
    });
});

// 组件卸载时清理图表实例和事件监听
onBeforeUnmount(() => {
    [answersInstance, acceptanceInstance, activityInstance, domainInstance].forEach(instance => {
        instance && instance.dispose();
    });
    window.removeEventListener('resize', resizeListener);
});


// Handle export
function handleExport() {
    loading.value = true
    // 准备请求参数
    const params = {
        startDate: formatDate(filterForm.dateRange?.[0]),
        endDate: formatDate(filterForm.dateRange?.[1]),
        specialtyTagId: specialtyTagId.value || ''
    };

    proxy.$http({
        url: proxy.$http.adornUrl("/admin/expert/statistics/export"),
        method: "get",
        params: proxy.$http.adornParams(params),
        responseType: 'blob'
    })
        .then(({ data }) => {
            // 创建一个Blob对象
            const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
            // 创建一个下载链接
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = `专家统计数据_${formatDate(filterForm.dateRange?.[0])}-${formatDate(filterForm.dateRange?.[1])}.xlsx`
            document.body.appendChild(link)
            link.click()
            // 清理
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)

            // ElMessage.success('导出成功')
        }).catch(() => {
            ElMessage.error('导出失败')
        }).finally(() => {
            loading.value = false
        })
}

// 示例：页面加载时调用（可根据实际业务触发）
onMounted(() => {
    // 假设有props.question.specialtyTagIds
    // fetchRecommendExperts(props.question.specialtyTagIds)
})

onMounted(() => {
    // fetchExpertStatistics();
    nextTick(() => {
        initCharts();
        resizeCharts();
        handleFilterChange(); // 初始化时获取所有图表数据
    });
    // 监听窗口resize
    resizeListener = () => {
        resizeCharts();
    };
    window.addEventListener('resize', resizeListener);


    fetchSpecialtyTags()
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeListener);
    // 销毁echarts实例，防止内存泄漏
    answersInstance && answersInstance.dispose();
    acceptanceInstance && acceptanceInstance.dispose();
    activityInstance && activityInstance.dispose();
    domainInstance && domainInstance.dispose();
});
</script>

<style lang="scss" scoped>
.mod-config {
    padding: 20px;

    .overview-stats {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 20px;
        margin-bottom: 20px;

        .stat-card {
            .stat-value {
                font-size: 24px;
                font-weight: bold;
                color: #303133;
                margin-bottom: 8px;
            }

            .stat-label {
                font-size: 14px;
                color: #909399;
                margin-bottom: 8px;
            }

            .stat-trend {
                font-size: 12px;
                color: #F56C6C;

                &.positive {
                    color: #67C23A;
                }
            }
        }
    }

    .filter-section {
        margin-bottom: 20px;
    }

    .charts-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 20px;

        .chart-card {
            .chart-title {
                font-size: 16px;
                font-weight: bold;
                color: #303133;
            }

            .chart {
                height: 300px;
                width: 100%;
            }
        }
    }

    .mt-20 {
        margin-top: 20px;
    }
}
</style>
